#include <stdio.h>
#include <windows.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define MaxX 78
#define MaxY 23
#define MaxD 100
typedef struct diemcao
{
	int diem; char ten[30];	
} dc;
bool body[MaxX+1][MaxY+1]; 
int dx[MaxD], dy[MaxD];
int x, y;
int Huong, Huongcu;
int Diem;
int Dai;
int speed, maxspeed;
int xthucan, ythucan;
int Ok;
unsigned char c;


void Khoitao()
{
	Diem=0;
	Dai=4;
	Ok=50;
	c=1;
	x=10; y=10;
	Huong=2; Huongcu=0;
	speed=150;  
	maxspeed=30; 
	int i,j;
	for (i=0; i<MaxX; i++)
		for (j=0; j<MaxY; j++) body[i][j]=false;
	body[x][y]=true;
	for(int i=0; i<Dai; i++) { dx[i]=x; dy[i]=y; }
	srand(time(NULL));
}
void gotoxy(short x, short y) 
{
	COORD pos = {x, y};
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}

void Vekhung()
{
	system("cls");
	for (int i=0; i<MaxX+2; i++) 
	{
		gotoxy(i,MaxY+1); printf("%c",219);
		gotoxy(i,0); printf("%c",219);
	}
	for (int i=0; i<MaxY+1; i++) 
	{
		gotoxy(MaxX+1,i); printf("%c",219);
		gotoxy(0,i); printf("%c",219);
	}
	gotoxy(70,0); printf(" DIEM: %d ", Diem);
	gotoxy(1,0); printf(" 1.MENU  ");
	gotoxy(34,0); printf(" S n A k E ");
}

void Move()
{
	Huongcu=Huong;
	if (kbhit())
		{
			c = getch();
			if (c==224)
			{
				c = getch();
				if (c==72) Huong=1;//y=y-1;
				if (c==75) Huong=0;//x=x-1;
				if (c==77) Huong=3;//x=x+1;
				if (c==80) Huong=2;//y=y+1;
			}
		}
		if( Huong+Huongcu==3) Huong=Huongcu;
		if (Huong==1) y=y-1;
		if (Huong==0) x=x-1;
		if (Huong==3) x=x+1;
		if (Huong==2) y=y+1;
}
void Datthucan()
{
	do
	{
		xthucan=rand()%MaxX+1; ythucan=rand()%MaxY+1;	
	}
	while (body[xthucan][ythucan]);
	gotoxy(xthucan,ythucan); 
	printf("%c",15);
}



void Ran()
{
	bool End=false;
	Datthucan();
	do
	{
		Sleep(speed);

		Move();
		
		if(body[x][y] || x==MaxX+1 || y==MaxY+1 || x==0 || y==0 || Dai==Ok || c=='1' ) End=true;
		
		
		if (x==xthucan && y==ythucan)
		{
			Dai++;
			if (speed > maxspeed) speed-=5;
			Diem= Diem + 1;
			gotoxy(77,0);
			printf("%d", Diem);
			Datthucan();
		}


		gotoxy(dx[0],dy[0]); printf(" "); body[dx[0]][dy[0]]=false;

		gotoxy(x,y); printf("%c",6); body[x][y]=true;
		
		for(int i=0; i<Dai; i++)
			{
				dx[i]=dx[i+1];
				dy[i]=dy[i+1];
			}
			dx[Dai]=x; dy[Dai]=y;

	}
	while (!End);
}

main()
{
	
	Vekhung();
	Ran();
}
